package com.example.bingobox.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.example.bingobox.R;
import com.example.bingobox.model.Task;
import androidx.core.content.ContextCompat;

public class ClockTimeSelector extends View {
    private Paint circlePaint;
    private Paint sectorPaint;
    private Paint textPaint;
    private Paint linePaint;
    private float radius;
    private float centerX;
    private float centerY;
    private float startAngle = 0;
    private float endAngle = 90;
    private boolean isDraggingStart = false;
    private boolean isDraggingEnd = false;
    private OnTimeChangedListener listener;
    private static final float DISABLED_START_ANGLE = 15f;  // 01:00 对应的角度
    private static final float DISABLED_END_ANGLE = 75f;    // 05:00 对应的角度
    private static final float MIN_ANGLE_DIFF = 2.5f;      // 10分钟对应的角度差
    private Paint disabledPaint;
    private static final float SNAP_ANGLE = 1.25f;  // 5分钟对应的角度 (15度/12)
    private static final float START_ANGLE = 75f;   // 05:00 对应的角度

    public interface OnTimeChangedListener {
        void onTimeChanged(int startHour, int startMinute, int endHour, int endMinute);
    }

    public ClockTimeSelector(Context context) {
        super(context);
        init();
    }

    public ClockTimeSelector(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        circlePaint.setColor(ContextCompat.getColor(getContext(), R.color.clock_selector_background));
        circlePaint.setStyle(Paint.Style.STROKE);
        circlePaint.setStrokeWidth(4);

        sectorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        sectorPaint.setColor(ContextCompat.getColor(getContext(), R.color.clock_selector_sector));
        sectorPaint.setStyle(Paint.Style.FILL);

        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(40);
        textPaint.setTextAlign(Paint.Align.CENTER);

        linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        linePaint.setStrokeWidth(8);

        disabledPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        disabledPaint.setColor(Color.LTGRAY);
        disabledPaint.setStyle(Paint.Style.FILL);
        disabledPaint.setAlpha(128);

        // 设置初始位置：蓝色指针在05:00，红色指针在01:00
        startAngle = DISABLED_END_ANGLE;
        endAngle = DISABLED_START_ANGLE;
    }

    @Override
    protected void onSizeChanged(int w, int h, int viewWidth, int viewHeight) {
        super.onSizeChanged(w, h, viewWidth, viewHeight);
        radius = Math.min(w, h) / 2f * 0.9f;
        centerX = w / 2f;
        centerY = h / 2f;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 绘制时钟圆盘
        canvas.drawCircle(centerX, centerY, radius, circlePaint);

        // 绘制禁用区域（01:00-05:00）
        RectF oval = new RectF(centerX - radius, centerY - radius, 
                              centerX + radius, centerY + radius);
        canvas.drawArc(oval, DISABLED_START_ANGLE - 90, 
            DISABLED_END_ANGLE - DISABLED_START_ANGLE, true, disabledPaint);

        // 绘制时间刻度和数字
        for (int i = 0; i < 24; i++) {
            float angle = i * 15 - 90; // 从12点钟方向开始，每小时15度
            double radians = Math.toRadians(angle);
            float x = (float) (centerX + Math.cos(radians) * radius);
            float y = (float) (centerY + Math.sin(radians) * radius);
            
            // 绘制刻度线
            float innerX = (float) (centerX + Math.cos(radians) * (radius - 20));
            float innerY = (float) (centerY + Math.sin(radians) * (radius - 20));
            canvas.drawLine(innerX, innerY, x, y, circlePaint);
            
            // 绘制小时数字
            float textX = (float) (centerX + Math.cos(radians) * (radius - 40));
            float textY = (float) (centerY + Math.sin(radians) * (radius - 40) + 15);
            canvas.drawText(String.valueOf(i), textX, textY, textPaint);
        }

        // 绘制选中的扇形区域
        float sweepAngle = (endAngle - startAngle + 360) % 360;
        canvas.drawArc(oval, startAngle - 90, sweepAngle, true, sectorPaint);

        // 绘制开始和结束指针
        drawHand(canvas, startAngle - 90, Color.BLUE);
        drawHand(canvas, endAngle - 90, Color.RED);
    }

    private void drawHand(Canvas canvas, float angle, int color) {
        double radians = Math.toRadians(angle);
        float x = (float) (centerX + Math.cos(radians) * radius);
        float y = (float) (centerY + Math.sin(radians) * radius);
        
        Paint handPaint = new Paint(linePaint);
        handPaint.setColor(color == Color.BLUE ? 
            ContextCompat.getColor(getContext(), R.color.clock_selector_start) : 
            ContextCompat.getColor(getContext(), R.color.clock_selector_end));
        
        // 绘制指针线
        canvas.drawLine(centerX, centerY, x, y, handPaint);
        
        // 在指针端点绘制标记
        float markerRadius = 16;  // 从12改为16
        canvas.drawCircle(x, y, markerRadius, handPaint);
        
        // 在标记内绘制文字
        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(24);  // 从16改为24
        textPaint.setTextAlign(Paint.Align.CENTER);
        float textY = y + textPaint.getTextSize() / 3;  // 调整文字垂直位置
        canvas.drawText(color == Color.BLUE ? "始" : "终", x, textY, textPaint);
    }

    private float snapToGrid(float angle) {
        // 将角度对齐到最近的5分钟刻度
        float snappedAngle = Math.round(angle / SNAP_ANGLE) * SNAP_ANGLE;
        
        // 确保不会小于05:00对应的角度
        if (snappedAngle < START_ANGLE) {
            snappedAngle = START_ANGLE;
        }
        
        return snappedAngle;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX() - centerX;
        float y = event.getY() - centerY;
        float touchAngle = (float) Math.toDegrees(Math.atan2(y, x)) + 90;
        if (touchAngle < 0) touchAngle += 360;

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                float startDiff = Math.abs(touchAngle - startAngle);
                float endDiff = Math.abs(touchAngle - endAngle);
                // 增大触摸判定范围
                if (startDiff < 20) {  // 从15改为20
                    isDraggingStart = true;
                } else if (endDiff < 20) {  // 从15改为20
                    isDraggingEnd = true;
                }
                break;

            case MotionEvent.ACTION_MOVE:
                if (isDraggingStart) {
                    // 处理开始指针的移动
                    float newStartAngle = snapToGrid(touchAngle);  // 对齐到网格
                    
                    // 确保不进入禁用区域
                    if (newStartAngle > DISABLED_START_ANGLE && newStartAngle < DISABLED_END_ANGLE) {
                        newStartAngle = DISABLED_END_ANGLE;
                    }
                    
                    // 确保与结束指针保持最小距离
                    float angleDiff = (endAngle - newStartAngle + 360) % 360;
                    if (angleDiff < MIN_ANGLE_DIFF) {
                        endAngle = (newStartAngle + MIN_ANGLE_DIFF) % 360;
                        if (endAngle > DISABLED_START_ANGLE && endAngle < DISABLED_END_ANGLE) {
                            endAngle = DISABLED_START_ANGLE;
                            newStartAngle = (DISABLED_START_ANGLE - MIN_ANGLE_DIFF + 360) % 360;
                        }
                    }
                    
                    startAngle = newStartAngle;
                    notifyTimeChanged();
                    invalidate();
                } else if (isDraggingEnd) {
                    // 处理结束指针的移动
                    float newEndAngle = snapToGrid(touchAngle);  // 对齐到网格
                    
                    // 确保不进入禁用区域
                    if (newEndAngle > DISABLED_START_ANGLE && newEndAngle < DISABLED_END_ANGLE) {
                        newEndAngle = DISABLED_START_ANGLE;
                    }
                    
                    // 确保与开始指针保持最小距离
                    float angleDiff = (newEndAngle - startAngle + 360) % 360;
                    if (angleDiff < MIN_ANGLE_DIFF) {
                        startAngle = (newEndAngle - MIN_ANGLE_DIFF + 360) % 360;
                        if (startAngle > DISABLED_START_ANGLE && startAngle < DISABLED_END_ANGLE) {
                            startAngle = DISABLED_END_ANGLE;
                            newEndAngle = (DISABLED_END_ANGLE + MIN_ANGLE_DIFF) % 360;
                        }
                    }
                    
                    endAngle = newEndAngle;
                    notifyTimeChanged();
                    invalidate();
                }
                break;

            case MotionEvent.ACTION_UP:
                isDraggingStart = false;
                isDraggingEnd = false;
                break;
        }
        return true;
    }

    private void notifyTimeChanged() {
        if (listener != null) {
            int startHour = (int) ((startAngle / 15) % 24);
            int startMinute = (int) ((startAngle % 15) * 4);
            int endHour = (int) ((endAngle / 15) % 24);
            int endMinute = (int) ((endAngle % 15) * 4);
            listener.onTimeChanged(startHour, startMinute, endHour, endMinute);
        }
    }

    public void setOnTimeChangedListener(OnTimeChangedListener listener) {
        this.listener = listener;
    }

    public void setTime(int startHour, int startMinute, int endHour, int endMinute) {
        startAngle = (startHour * 15 + startMinute / 4f);
        endAngle = (endHour * 15 + endMinute / 4f);
        invalidate();
    }

    public void getTime(Task.TimeLabel timeLabel) {
        timeLabel.setStartHour((int) ((startAngle / 15) % 24));
        timeLabel.setStartMinute((int) ((startAngle % 15) * 4));
        timeLabel.setEndHour((int) ((endAngle / 15) % 24));
        timeLabel.setEndMinute((int) ((endAngle % 15) * 4));
    }

    public int getStartHour() {
        return (int) ((startAngle / 15) % 24);
    }

    public int getStartMinute() {
        return (int) ((startAngle % 15) * 4);
    }

    public int getEndHour() {
        return (int) ((endAngle / 15) % 24);
    }

    public int getEndMinute() {
        return (int) ((endAngle % 15) * 4);
    }
} 